package com.ftqh.project.travel.security.controller;

import com.ftqh.project.travel.security.entity.User;
import com.ftqh.project.travel.security.service.UserService;
import com.ftqh.project.travel.security.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

@RestController
@SessionAttributes("authorizationRequest")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserValidator userValidator;
    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = {"/", "/index"})
    public ModelAndView welcome() {
        return new ModelAndView("index");
    }

    @GetMapping("/login")
    public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
        return new ModelAndView("login", "error", error);
    }
    @GetMapping("/register")
    public ModelAndView register() {
        //userService.save(user);
        return new ModelAndView("register");
    }

    @GetMapping("/addtravel")
    public ModelAndView addTravel() {
        return new ModelAndView("addtravel");
    }

    @GetMapping("/search")
    public ModelAndView search() {
        return new ModelAndView("search");
    }

    @PostMapping(value = "/register")
    public ResponseEntity<?> addUser(User user, BindingResult bindingResult){
        userValidator.validate(user, bindingResult);
        Map<String, Object> resultMap = new HashMap<>();
        if (bindingResult.hasErrors()) {
            resultMap.put("status", "failure");
            Locale locale = LocaleContextHolder.getLocale();
            Map<String, String> errorMap = new HashMap<>();
            for (ObjectError objectError: bindingResult.getAllErrors()){
                String code = objectError.getCode();
                errorMap.put(code,messageSource.getMessage(code, null, locale));
            }
            resultMap.put("error", errorMap);
            return new ResponseEntity(resultMap,HttpStatus.OK);
        }
        resultMap.put("status", "ok");
        userService.save(user);

        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

}
